<?php

namespace app\admin\controller\rent;

use app\common\controller\Backend;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Items extends Backend
{
    
    /**
     * Items模型对象
     * @var \app\admin\model\rent\Items
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\rent\Items;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
            ->with(['seconddecoration','newhousebuildingtypes','authcops','admin','newhousebuilding','updateadmin'])
            ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
            ->with(['seconddecoration','newhousebuildingtypes','authcops','admin','newhousebuilding','updateadmin'])
            ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach($list as $row){
                $row->admin->visible(['nickname']);
                $row->getRelation('updateadmin')->visible(['nickname']);
                unset($row->mobile);
                // limit
                if($row->view_level==3){
                    // 个人私房
                    if($row->add_userid != $this->auth->id){
                        $row->dong='';
                        $row->shi='';
                    }
                }
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $this->view->assign('second_sort', config('site.configgroup')['second_sort']);
        $this->view->assign('second_sort_name', config('site.configgroup')['second_sort_name']);
        $this->view->assign('second_show_fanghao',config('site.second_show_fanghao'));
        return $this->view->fetch();
    }
      /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['add_userid'] = $this->auth->id;
                    $params['add_cop_id'] = $this->auth->cop_id;
                    $params['add_time']=time();
                    $params['add_ip']  = $this->request->ip();
                    
                    $params['update_userid']=$this->auth->id;
                    $params['update_time']=time();
                    $params['update_cop_id'] = $this->auth->cop_id;
                    $params['update_ip']  = $this->request->ip();

                    if($params['building_id']<=0){
                        $this->error('楼盘名称错误');
                    }
                    // 判重
                    $count = (new \app\admin\model\second\Items())->where("building_id=" . $params['building_id'] . " and dong='" . $params['dong'] . "' and shi='" . $params['shi'] . "'")->count();
                    if($count>0){
                        $this->error('房源已经存在');
                    }

                    $result = $this->model->allowField(true)->save($params);
                    // 更新楼盘房源数量
                    $building = new \app\admin\controller\second\Buildings;
                    $building->updateCount($params['building_id']);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('录入成功');
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        // 是否启用填表助手 
        $assist = config('site.second_assistant');
        $this->assign('assist',$assist);
        return $this->view->fetch();
    }
    /**
     * 某栋房房源是否已经存在
     */
    public function checkExistsDongShi(){
        $building_id = $this->request->post('building_id');
        $dong        = $this->request->post('dong');
        $shi         = $this->request->post('shi');
        $cop_id      = $this->auth->cop_id;
        $list = (new \app\admin\model\second\Items())->where("building_id=" . $building_id . " and dong='" . $dong . "' and shi='" . $shi . "'")->select();  // and add_cop_id=" . $cop_id
        if(count($list)>0){
            return json(['exists'=>true,'id'=>$list[0]->id,'mobile'=>$list[0]->mobile]);
        }else
            return json(['exists'=>false]);
    }
    /**
     * 某号码房源是否已经存在
     */
    public function checkExistsMobile(){
        $mobile = $this->request->post('mobile');
        $list = (new \app\admin\model\second\Items())->where("mobile like '%" . $mobile . "'")->select();
        $ids = [];
        foreach ($list as $row) {
            $ids[] = ['id'=>$row->id,'dong'=>$row->dong,'shi'=>$row->shi,'building_name'=>$row->newhousebuilding->building_name];
        }
        if(count($list)>0){
            return json(['exists'=>true,'ids'=>$ids]);
        }else
            return json(['exists'=>false]);
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if($params['building_id']<=0){
                        $this->error('楼盘名称错误');
                    }
                    // 判重
                    $count = (new \app\admin\model\second\Items())->where("id<>" . $ids . " and building_id=" . $params['building_id'] . " and dong='" . $params['dong'] . "' and shi='" . $params['shi'] . "'")->count();
                    if($count>0){
                        $this->error('房源已经存在');
                    }
                    if(empty($params['view_level'])){
                        $params['view_level']=0;
                    }

                    $params['update_userid']=$this->auth->id;
                    if($this->auth->id!=18){ //TODO: 时翠兰改不更新时间 2020-5-7临时这么改
                        $params['update_time']=time();
                    }
                    $params['update_cop_id'] = $this->auth->cop_id;
                    $params['update_ip']  = $this->request->ip();
                    $result = $row->allowField(true)->save($params);
                    // 更新楼盘房源数量
                    $building = new \app\admin\controller\second\Buildings;
                    $building->updateCount($params['building_id']);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
      /**
     * 查看出租房源
     */
    public function view($ids){
        // $row = $this->model->get($ids);
        $list=$this->model
                    ->with(['seconddecoration','newhousebuildingtypes','authcops','admin','newhousebuilding'])
                    ->where(['mf_rent_items.id'=>$ids])
                    ->select();
        if(count($list)==0){
            $this->error(__('No Results were found'));
        }
        $row=$list[0];
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $building=\app\admin\model\second\Buildings::get($row->building_id);
        
        // 权限
        if($row->view_level==3){
            // 个人私房
            if($row->add_userid!=$this->auth->id){
                $row->mobile='私房(无权限查看号码)';
                $row->dong='';
                $row->shi='';
            }
        }else if($row->view_level==2){
            //TODO: 本门店
        }else if($row->view_level==1){
            // 本公司
            if($row->add_cop_id!=$this->auth->cop_id){
                $row->mobile='私房(无权限查看号码)';
                $row->dong='';
                $row->shi='';
            }
        }
        $creator = \app\admin\model\Admin::get($row->add_userid);
        if(empty($creator)){
            $creatorName='';
        }else{
            $creatorName = $creator->nickname;
        }
        $createCop = \app\admin\model\auth\Cops::get($row->add_cop_id);
        if(empty($createCop)){
            $copName = '';
        }else{
            $copName = $createCop->cop_name;
        }
        $this->view->assign("row",$row);
        $this->view->assign('creatorName',$creatorName);
        $this->view->assign('copName',$copName);
        return $this->view->fetch('view');
    }
}
